<?php

namespace TpAmis\build;

use TpAmis\Renderers\Amis;
use TpAmis\Renderers\BaseApi;
use TpAmis\Renderers\BaseRenderer;
use TpAmis\Traits\BaseApiTrait;
use TpAmis\Traits\ButtonsTrait;

class FormBuilder extends BaseRenderer
{
    use BaseApiTrait;
    use ButtonsTrait;

    protected array $body = [];
    protected array $data = [];
    protected object $amis;
    protected string $primaryKey = 'id';


    public function __construct()
    {
        $this->amis = amis()->Form();

        $this->setApi($this->BaseApiPost('index'));

    }

    public static function amis()
    {
        return new self();
    }

    protected BaseApi $api;

    /**
     * @param BaseApi $api
     * @return $this
     */
    public function setApi(BaseApi $api): FormBuilder
    {
        $this->api = $api;
        return $this;
    }

    /**
     * 设置表单数据
     * @param mixed $data
     * @return void
     */
    public function data($data = [])
    {
        $this->data = $data;
    }


    protected array $actions = [];

    public function setActions($label = '', $type = '', $extend_attr = [])
    {
        $items = amis()->Action()->label($label)->actionType($type);
        $this->extend_attr($items, $extend_attr);
        $this->actions[] = $items;
        return $this;
    }

    /**
     * 设置提交按钮
     * @param string $label 按钮名称
     * @param array $extend_attr 扩展属性
     * @param string $url 请求地址
     * @param array $vars 请求参数
     * @param bool $suffix 是否添加后缀
     * @param bool $domain 是否添加域名
     * @return $this
     */
    public function setSubmitAction($label = '保存', $extend_attr = [], $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        if (is_object($label)) {
            $items = $label;
        } else {
            if (is_string($url)) {
                if (!$this->containsAny($label, ['get:', 'post:', 'put:', 'delete:'])) {
                    $url = $this->BaseApiPost($url, $vars, $suffix, $domain);
                }
            }

            $items = amis()->Action()->label($label)->actionType('ajax')->api($url);
        }
        $this->extend_attr($items, $extend_attr);
        $this->actions[] = $items;
        return $this;
    }
    private function containsAny($string, $array)
    {
        foreach ($array as $value) {
            if (strpos($string, $value) !== false) {
                return true;
            }
        }
        return false;
    }
    public function fetch()
    {
        $this->amis->api($this->api)
            ->submitText('')
            ->body($this->body)
            ->actions($this->actions);

        return $this->amis;
    }


    /**
     * @param string $name
     * @param string $label
     * @param string $type
     * @param string $description
     * @return $this
     */
    public function addFormItem(string $name = '', string $label = '', string $type = 'text', $description = ''): FormBuilder
    {

        $itemsName = strtolower($type) . 'Control';
        if (method_exists(Amis::class, $itemsName)) {

            $args = array_slice(func_get_args(), 4);

            $this->$itemsName($name, $label, $description, ...$args);
        } else if (method_exists(Amis::class, $itemsName)) {

            $items = amis()->$itemsName($name, $label)->description($description)->placeholder('输入' . $label);

            $this->body[] = $items;
        }
        return $this;
    }
    /**
     * 获取调用该方法时的参数名和参数值
     */
    protected function myFunction($functionName)
    {


        // 获取函数定义时的参数名
        $reflection = new \ReflectionMethod(__CLASS__, $functionName);
        $parameters = $reflection->getParameters();

        // 打印参数名和对应的值
        foreach ($parameters as $index => $parameter) {
            $paramName = $parameter->getName();
            $paramValue = $args[$index] ?? null;
            echo "Parameter name: $paramName, Value: " . print_r($paramValue, true) . "\n";
        }
    }
    protected function extend_attr(&$items, array $extend_attr = [])
    {
        foreach ($extend_attr as $key => $value) {
            $items->set($key, $value);
        }
        return $items;
    }

    /**
     * @param array $columns
     * @return $this
     */
    public function addFormItems(array $columns = []): FormBuilder
    {
        foreach ($columns as $options) {
            call_user_func_array([$this, 'addFormItem'], $options);
        }
        return $this;
    }



    public function __call($name, $arguments)
    {
        if (strpos($name, 'set') !== false) {
            $name = str_replace('set', '', $name);

            $this->amis = $this->amis->$name(...$arguments);
        }


        return $this;
    }


    /**
     * 文本表单
     * @param string $name
     * @param string $label
     * @param mixed $description
     * @param mixed $extend_attr 扩展属性
     * @return \TpAmis\build\FormBuilder
     */
    function TextControl(string $name = '', string $label = '', $description = '', $extend_attr = []): FormBuilder
    {
        $items = amis()->TextControl($name, $label)->description($description)->placeholder('输入' . $label)->showCounter();
        $this->extend_attr($items, $extend_attr);
        $this->body[] = $items;
        return $this;
    }

    function NumberControl(string $name = '', string $label = '', $description = '', $extend_attr = []): FormBuilder
    {
        $items = amis()->NumberControl($name, $label)->description($description)->placeholder('输入' . $label)->showCounter();
        $this->extend_attr($items, $extend_attr);
        $this->body[] = $items;
        return $this;
    }

}
